package com.siwei.apply.controller;

import com.siwei.apply.domain.res.YdysyxzRes;
import com.siwei.apply.domain.vo.YdysyxzUpdateVo;
import com.siwei.apply.domain.vo.YdysyxzVo;
import com.siwei.apply.service.YdysyxzService;
import com.siwei.common.core.domain.R;
import com.siwei.common.core.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用地预审与选址 控制器
 * 单独选址第一步
 */
@RestController
@RequestMapping("/ydysyxz")
public class YdysyxzController extends BaseController {
    @Autowired
    private YdysyxzService ydysyxzService;

    /**
     * 添加用地预审与选址信息
     */
    @PostMapping()
    public R<Map> Add(@RequestBody YdysyxzVo ydysyxzVo) {
        try {
            // 判断是否存在
            Boolean b = ydysyxzService.isExit(ydysyxzVo.getProjectId());
            if (b) {
                return R.fail("此项目已添加用地预审与选址");
            }
            // 添加
            String id = ydysyxzService.add(ydysyxzVo);
            Map<String, String> map = new HashMap<>();
            map.put("id", id);
            return R.ok(map);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取用地预审与选址信息
     *
     * @param projectId 项目ID
     * @return 用地预审与选址信息
     */
    @GetMapping("/{projectId}")
    public R<YdysyxzRes> Get(@PathVariable String projectId) {
        try {
            return R.ok(ydysyxzService.get(projectId));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 通过主键id获取用地预审与选址信息，返回结果与按projectId查询一致
     */
    @GetMapping("/id/{id}")
    public R<YdysyxzRes> GetById(@PathVariable String id) {
        try {
            return R.ok(ydysyxzService.getById(id));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 更新用地预审与选址信息
     *
     * @param ydysyxzUpdateVo 用地预审与选址视图对象
     * @return 操作结果
     */
    @PutMapping()
    public R<Void> Update(@RequestBody YdysyxzUpdateVo ydysyxzUpdateVo) {
        try {
            ydysyxzService.update(ydysyxzUpdateVo);
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 更新用地预审与选址的上链状态
     */
    @PutMapping("/onchain")
    public R<Void> updateHasOnchain(@RequestBody Map<String, Object> params) {
        try {
            String id = (String) params.get("id");
            Boolean hasOnchain = (Boolean) params.get("hasOnchain");
            ydysyxzService.updateHasOnchain(id, hasOnchain);
            return R.ok();
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }
}
